package com.ht.medicaltreatment.activity

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.SearchResultAdapter
import com.ht.medicaltreatment.bean.SearchResultBean
import com.ht.medicaltreatment.viewmodel.SearchResultViewModel
import kotlinx.android.synthetic.main.activity_search_result_layout.etSearch
import kotlinx.android.synthetic.main.activity_search_result_layout.recyclerView

class SearchResultActivity:BaseActivity(), TextWatcher, OnItemClickListener {
    private val model by viewModels<SearchResultViewModel>()
    override fun getLayoutId() = R.layout.activity_search_result_layout

    private lateinit var adapter:SearchResultAdapter
    override fun init() {
        StatusBarCompat.setStatusBarColor(this,getColor(R.color.blueDeep))
        adapter = SearchResultAdapter()
        etSearch.requestFocus()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
        etSearch.addTextChangedListener(this)
        adapter.setOnItemClickListener(this)
        adapter.setEmptyView(R.layout.item_empty_view)
        adapter.onAttachedToRecyclerView(recyclerView)
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        model.search(s.toString(),{
            adapter.setNewInstance(it)
        },{
            adapter.setNewInstance(null)
        })
    }

    override fun afterTextChanged(s: Editable?) {
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as SearchResultBean
        val intent = Intent()
        intent.putExtra("name",item.assetName)
        intent.putExtra("uid",item.rfidCode)
        setResult(RESULT_OK,intent)
        finish()
    }
}